/*! \page license
 *
 * Copyright (c) 2011, Blaise Lengrand
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this
 * list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 * Neither the name of `snWin' nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior
 * written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

const rss_feed = {
  'display_name': "RSS",
  'author': "Blaise Lengrand",
  'id': "rss",
  'default_color': "",
  'ep': {
    'connect': rss_connect,
    'is_connected': rss_is_connected,
    'update': rss_update,
    'previous': rss_previous,
    'add_fields': rss_add_fields
  },
  'session': {
    'url': null,
    'username': null,
    'password': null
  },
  'update_rate_s': 60,
  'options': {
    'compare_entry_content': true
  }
};

//! Add the feed to the list
feed_available[rss_feed.id] = rss_feed;

function rss_is_connected(feed_id)
{
  return true;
}

function rss_connect(feed_id, context)
{
  // If no display name is set, choose the domain name as display name
  if (!context.display_name)
    context.display_name = $.url.parse(context.url).host;
  // Register the feed
  feed_register(feed_id, rss_feed, context);
  // Creates a flag to tells that the feed has never been read
  feed[feed_id].rss_is_read = false;
  // This is the most recent feed date (it will decide if a new entry has to be updated or not)
  feed[feed_id].rss_data = 0;
  // Test feed connectivity
  rss_get_feed(feed_id, true);
}

function rss_previous(feed_id)
{
  // If the feed has already been read, just exit and notify the core
  if (feed[feed_id].rss_is_read)
    return feed_callback(feed_id);
  // Process the data previously acquired
  rss_process_data(feed_id, feed[feed_id].rss_data);
}

function rss_update(feed_id)
{
  rss_get_feed(feed_id);
}

function rss_process_data(feed_id, data)
{
  // Test the feed
  if (!feed_id || !feed[feed_id])
    return feed_log("Invalid feed", null, "error");
  // The feed has been read at least once
  feed[feed_id].rss_is_read = true;
  // On success
  $.each(data, function(i, item) {
    // Makes sure the entry is valid
    if (!item || typeof(item.date) == "undefined")
      return feed_log("Feed with invalid entry - item: " + item + " - item.date: " + item.date, feed_id, "error");
    // Test the date of this item, if it is newer than the current feed date, print it
    if (item.date > feed[feed_id].date.newest)
      // Print the entries
      feed_entry_add(item, feed_id);
  });
  feed_callback(feed_id);
}

function rss_get_feed(feed_id, test_connectivity)
{
  // Url to the feed parser
  var parsed_url = $.url.parse(feed[feed_id].session.url);
  var built_url = $.url.build({
      "protocol": (parsed_url.protocol)?parsed_url.protocol:"http",
      "user": (parsed_url.user)?parsed_url.user:feed[feed_id].session.username,
      "password": (parsed_url.password)?parsed_url.password:feed[feed_id].session.password,
      "host": parsed_url.host,
      "port": (parsed_url.port)?parsed_url.port:null,
      "path": parsed_url.path,
      "query": parsed_url.query,
      "anchor": parsed_url.anchor
  });
  url = "system/pages/social/rss/get.php?url=" + escape(built_url);
  feed_log("Feed url `" + url + "'", feed_id);

  var success_fct = function (data) {
    rss_process_data(feed_id, data);
  };
  if (test_connectivity == true)
  {
    success_fct = function (data) {
      feed[feed_id].rss_data = data;
      feed_connected(feed_id);
      feed_log("Feed connected", feed_id);
      return;
    };
  }

  // Get feed information
  feed_get_json(feed_id, url,
    success_fct
  );
}

function rss_add_fields()
{
  var div_container = document.createElement("div");
  var html = "<span class=\"required\">Feed URL: <input name=\"url\" class=\"required\" type=\"text\" /></span><br />";
  html += "<span class=\"comment\">Looking for a feed? <a href=\"http://ctrlq.org/\">http://ctrlq.org/</a></span>";
  html += "<hr />";
  html += "Only if authentication is required<br />";
  html += "<table>";
  html += "<tr><td>Username: </td><td><input name=\"username\" type=\"text\" /></td></tr>";
  html += "<tr><td>Password: </td><td><input name=\"password\" type=\"password\" /></td></tr>";
  html += "</table>";
  div_container.innerHTML = html;
  return div_container;
}
